import React, { useState, useEffect } from 'react';
import {
  ProDescriptions,
  ProCard,
  ProForm,
  ProFormText,
  ProFormSelect,
  ProFormTextArea,
} from '@ant-design/pro-components';
import {
  Button,
  Space,
  Modal,
  message,
  Tag,
  Spin,
  Row,
  Col,
  Timeline,
  Avatar,
  Divider,
} from 'antd';
import {
  ArrowLeftOutlined,
  EditOutlined,
  DeleteOutlined,
  UserOutlined,
  MailOutlined,
  PhoneOutlined,
  TeamOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import { useNavigate, useParams } from 'umi';
import dayjs from 'dayjs';

// 用户详情数据类型
interface UserDetail {
  id: string;
  name: string;
  email: string;
  phone: string;
  department: string;
  position: string;
  status: 'active' | 'inactive';
  createTime: string;
  lastLoginTime?: string;
  avatar?: string;
  description?: string;
  address?: string;
  birthday?: string;
  skills: string[];
  projects: Array<{
    id: string;
    name: string;
    role: string;
    startTime: string;
    endTime?: string;
    status: 'ongoing' | 'completed' | 'paused';
  }>;
  activities: Array<{
    id: string;
    action: string;
    time: string;
    description: string;
  }>;
}

// 使用MCP服务器辅助开发的用户详情页面
// 开发时间预估：约20分钟（相比手动版本的1.5小时+）
const MCPAssistedUserDetail: React.FC = () => {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const [form] = ProForm.useForm();

  // 状态管理
  const [loading, setLoading] = useState(true);
  const [user, setUser] = useState<UserDetail | null>(null);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);

  // 选项配置 - 通过MCP快速获取配置
  const departmentOptions = [
    { label: '技术部', value: 'tech' },
    { label: '产品部', value: 'product' },
    { label: '运营部', value: 'operation' },
    { label: '市场部', value: 'marketing' },
    { label: '财务部', value: 'finance' },
  ];

  const statusOptions = [
    { label: '活跃', value: 'active' },
    { label: '非活跃', value: 'inactive' },
  ];

  const skillsOptions = [
    'React', 'Vue', 'Angular', 'Node.js', 'Python', 'Java', 
    'JavaScript', 'TypeScript', 'HTML/CSS', 'UI/UX设计',
    '项目管理', '产品设计', '数据分析', '市场营销'
  ];

  // 模拟获取用户详情
  const fetchUserDetail = async (userId: string) => {
    setLoading(true);
    try {
      // 模拟API延迟
      await new Promise(resolve => setTimeout(resolve, 800));
      
      // 模拟用户详情数据
      const mockUser: UserDetail = {
        id: userId,
        name: `用户${userId.replace('user_', '')}`,
        email: `user${userId.replace('user_', '')}@example.com`,
        phone: `138${userId.replace('user_', '').padStart(8, '0')}`,
        department: departmentOptions[parseInt(userId.replace('user_', '')) % departmentOptions.length].value,
        position: `高级工程师`,
        status: parseInt(userId.replace('user_', '')) % 3 === 0 ? 'inactive' : 'active',
        createTime: dayjs().subtract(parseInt(userId.replace('user_', '')), 'day').format('YYYY-MM-DD HH:mm:ss'),
        lastLoginTime: parseInt(userId.replace('user_', '')) % 2 === 0 
          ? dayjs().subtract(parseInt(userId.replace('user_', '')) % 7, 'day').format('YYYY-MM-DD HH:mm:ss') 
          : undefined,
        avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${userId}`,
        description: '这是一位优秀的员工，在团队中发挥着重要作用。具有丰富的工作经验和强烈的责任心。',
        address: '北京市朝阳区建国路88号',
        birthday: '1990-05-15',
        skills: ['React', 'TypeScript', 'Node.js', '项目管理'].slice(0, parseInt(userId.replace('user_', '')) % 4 + 1),
        projects: [
          {
            id: 'proj_1',
            name: '电商平台重构项目',
            role: '前端负责人',
            startTime: '2023-01-15',
            endTime: '2023-06-30',
            status: 'completed'
          },
          {
            id: 'proj_2',
            name: '用户体验优化项目',
            role: '核心开发',
            startTime: '2023-07-01',
            status: 'ongoing'
          }
        ],
        activities: [
          {
            id: 'act_1',
            action: '登录系统',
            time: dayjs().subtract(2, 'hour').format('YYYY-MM-DD HH:mm'),
            description: '用户成功登录系统'
          },
          {
            id: 'act_2',
            action: '更新个人信息',
            time: dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm'),
            description: '用户更新了联系方式'
          },
          {
            id: 'act_3',
            action: '创建项目',
            time: dayjs().subtract(3, 'day').format('YYYY-MM-DD HH:mm'),
            description: '用户创建了新的项目'
          }
        ]
      };

      setUser(mockUser);
    } catch (error) {
      message.error('获取用户详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 保存编辑 - 利用ProForm的内置处理
  const handleEdit = async (values: any) => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      message.success('编辑成功');
      setEditModalVisible(false);
      
      // 重新获取用户详情
      if (id) {
        fetchUserDetail(id);
      }
      return true;
    } catch (error) {
      message.error('编辑失败');
      return false;
    }
  };

  // 删除用户
  const handleDelete = async () => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 300));
      
      message.success('删除成功');
      setDeleteModalVisible(false);
      
      // 返回列表页
      navigate('/mcp-crud');
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 获取部门名称
  const getDepartmentName = (value: string) => {
    const dept = departmentOptions.find(item => item.value === value);
    return dept?.label || value;
  };

  // 获取项目状态颜色和文本
  const getProjectStatusConfig = (status: string) => {
    const configs = {
      completed: { color: 'green', text: '已完成' },
      ongoing: { color: 'blue', text: '进行中' },
      paused: { color: 'orange', text: '暂停' },
    };
    return configs[status as keyof typeof configs] || { color: 'default', text: status };
  };

  // 初始化数据
  useEffect(() => {
    if (id) {
      fetchUserDetail(id);
    }
  }, [id]);

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!user) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <h3>用户不存在</h3>
        <Button onClick={() => navigate('/mcp-crud')}>返回列表</Button>
      </div>
    );
  }

  return (
    <div style={{ padding: 24 }}>
      {/* 头部操作区 - 使用ProCard简化布局 */}
      <ProCard style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Button 
            icon={<ArrowLeftOutlined />} 
            onClick={() => navigate('/mcp-crud')}
          >
            返回列表
          </Button>
          <Space>
            <Button 
              type="primary" 
              icon={<EditOutlined />}
              onClick={() => {
                form.setFieldsValue(user);
                setEditModalVisible(true);
              }}
            >
              编辑
            </Button>
            <Button 
              danger
              icon={<DeleteOutlined />}
              onClick={() => setDeleteModalVisible(true)}
            >
              删除
            </Button>
          </Space>
        </div>
      </ProCard>

      <Row gutter={[16, 16]}>
        {/* 基本信息 - 使用ProDescriptions简化描述列表 */}
        <Col span={16}>
          <ProCard title="基本信息" style={{ marginBottom: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 24 }}>
              <Avatar 
                size={80} 
                src={user.avatar} 
                icon={<UserOutlined />}
                style={{ marginRight: 16 }}
              />
              <div>
                <h2 style={{ margin: 0, marginBottom: 8 }}>{user.name}</h2>
                <Tag color={user.status === 'active' ? 'green' : 'red'}>
                  {user.status === 'active' ? '活跃' : '非活跃'}
                </Tag>
              </div>
            </div>
            
            {/* 使用ProDescriptions替代手动的Descriptions */}
            <ProDescriptions
              column={2}
              bordered
              dataSource={user}
              columns={[
                {
                  title: '邮箱',
                  key: 'email',
                  dataIndex: 'email',
                  render: (text) => (
                    <>
                      <MailOutlined style={{ marginRight: 8 }} />
                      {text}
                    </>
                  ),
                },
                {
                  title: '手机号',
                  key: 'phone',
                  dataIndex: 'phone',
                  render: (text) => (
                    <>
                      <PhoneOutlined style={{ marginRight: 8 }} />
                      {text}
                    </>
                  ),
                },
                {
                  title: '部门',
                  key: 'department',
                  dataIndex: 'department',
                  render: (text) => (
                    <>
                      <TeamOutlined style={{ marginRight: 8 }} />
                      {getDepartmentName(text)}
                    </>
                  ),
                },
                {
                  title: '职位',
                  key: 'position',
                  dataIndex: 'position',
                },
                {
                  title: '地址',
                  key: 'address',
                  dataIndex: 'address',
                  span: 2,
                  render: (text) => text || '-',
                },
                {
                  title: '生日',
                  key: 'birthday',
                  dataIndex: 'birthday',
                  render: (text) => text || '-',
                },
                {
                  title: '创建时间',
                  key: 'createTime',
                  dataIndex: 'createTime',
                  render: (text) => (
                    <>
                      <ClockCircleOutlined style={{ marginRight: 8 }} />
                      {text}
                    </>
                  ),
                },
                {
                  title: '最后登录',
                  key: 'lastLoginTime',
                  dataIndex: 'lastLoginTime',
                  span: 2,
                  render: (text) => text ? (
                    <>
                      <CheckCircleOutlined style={{ marginRight: 8 }} />
                      {text}
                    </>
                  ) : '-',
                },
                {
                  title: '个人描述',
                  key: 'description',
                  dataIndex: 'description',
                  span: 2,
                  render: (text) => text || '-',
                },
                {
                  title: '技能标签',
                  key: 'skills',
                  dataIndex: 'skills',
                  span: 2,
                  render: (skills: string[]) => 
                    skills.length > 0 ? (
                      skills.map(skill => (
                        <Tag key={skill} color="blue" style={{ marginBottom: 4 }}>
                          {skill}
                        </Tag>
                      ))
                    ) : '-',
                },
              ]}
            />
          </ProCard>

          {/* 项目经历 - 使用ProCard简化布局 */}
          <ProCard title="项目经历">
            {user.projects.length > 0 ? (
              user.projects.map(project => {
                const statusConfig = getProjectStatusConfig(project.status);
                return (
                  <ProCard 
                    key={project.id}
                    size="small" 
                    style={{ marginBottom: 8 }}
                    extra={
                      <Tag color={statusConfig.color}>
                        {statusConfig.text}
                      </Tag>
                    }
                  >
                    <h4 style={{ margin: 0, marginBottom: 8 }}>{project.name}</h4>
                    <p style={{ margin: 0, color: '#666' }}>
                      角色: {project.role} | 
                      时间: {project.startTime} ~ {project.endTime || '至今'}
                    </p>
                  </ProCard>
                );
              })
            ) : (
              <div style={{ textAlign: 'center', color: '#999', padding: 20 }}>
                暂无项目经历
              </div>
            )}
          </ProCard>
        </Col>

        {/* 活动时间线 - 使用ProCard包装 */}
        <Col span={8}>
          <ProCard title="最近活动">
            <Timeline>
              {user.activities.map(activity => (
                <Timeline.Item key={activity.id}>
                  <div style={{ marginBottom: 8 }}>
                    <strong>{activity.action}</strong>
                  </div>
                  <div style={{ color: '#666', fontSize: 12, marginBottom: 4 }}>
                    {activity.time}
                  </div>
                  <div style={{ color: '#999', fontSize: 12 }}>
                    {activity.description}
                  </div>
                </Timeline.Item>
              ))}
            </Timeline>
          </ProCard>
        </Col>
      </Row>

      {/* 编辑弹窗 - 使用ProForm简化表单开发 */}
      <Modal
        title="编辑用户"
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false);
          form.resetFields();
        }}
        footer={null}
        width={800}
      >
        <ProForm
          form={form}
          onFinish={handleEdit}
          layout="vertical"
          submitter={{
            searchConfig: {
              resetText: '取消',
              submitText: '保存',
            },
            resetButtonProps: {
              onClick: () => {
                setEditModalVisible(false);
                form.resetFields();
              },
            },
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <ProFormText
                name="name"
                label="姓名"
                rules={[{ required: true, message: '请输入姓名' }]}
                placeholder="请输入姓名"
              />
            </Col>
            <Col span={12}>
              <ProFormText
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入正确的邮箱格式' },
                ]}
                placeholder="请输入邮箱"
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <ProFormText
                name="phone"
                label="手机号"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
                ]}
                placeholder="请输入手机号"
              />
            </Col>
            <Col span={12}>
              <ProFormSelect
                name="department"
                label="部门"
                rules={[{ required: true, message: '请选择部门' }]}
                options={departmentOptions}
                placeholder="请选择部门"
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <ProFormText
                name="position"
                label="职位"
                rules={[{ required: true, message: '请输入职位' }]}
                placeholder="请输入职位"
              />
            </Col>
            <Col span={12}>
              <ProFormSelect
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
                options={statusOptions}
                placeholder="请选择状态"
              />
            </Col>
          </Row>
          <ProFormText
            name="address"
            label="地址"
            placeholder="请输入地址"
          />
          <ProFormSelect
            name="skills"
            label="技能标签"
            mode="multiple"
            options={skillsOptions.map(skill => ({ label: skill, value: skill }))}
            placeholder="请选择技能标签"
          />
          <ProFormTextArea
            name="description"
            label="个人描述"
            placeholder="请输入个人描述"
            fieldProps={{ rows: 3 }}
          />
        </ProForm>
      </Modal>

      {/* 删除确认弹窗 */}
      <Modal
        title="删除确认"
        open={deleteModalVisible}
        onOk={handleDelete}
        onCancel={() => setDeleteModalVisible(false)}
        okText="确定删除"
        cancelText="取消"
        okButtonProps={{ danger: true }}
      >
        <p>确定要删除用户 <strong>{user.name}</strong> 吗？</p>
        <p style={{ color: '#ff4d4f' }}>此操作不可恢复，请谨慎操作。</p>
      </Modal>
    </div>
  );
};

export default MCPAssistedUserDetail;